import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/home/Home.vue'
import None404 from '@/views/None404.vue'
import Login from '@/views/login/Login.vue'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect: '/wellcome',
    children: [
      {
        path: 'wellcome',
        name: 'wellcome',
        component: () => import('@/views/Wellcome/Wellcome.vue'),
      },
      {
        path: 'users',
        name: 'users',
        component: () => import('@/views/users/Users.vue'),
      },

      {
        path: 'rights',
        name: 'rights',
        component: () => import('@/views/rights/right-list/RightList.vue'),
      },
      {
        path: 'roles',
        name: 'roles',
        component: () => import('@/views/rights/role-list/RoleList.vue'),
      },
      {
        path: 'goods',
        name: 'goods',
        component: () => import('@/views/goods/goods-info/GoodsInfo.vue'),
      },
      {
        path: 'goodsadd',
        name: 'goodsadd',
        component: () =>
          import('@/views/goods/goods-info/components/GoodsInfoAdd.vue'),
      },
      {
        path: 'params',
        name: 'params',
        component: () => import('@/views/goods/goods-params/GoodsParams.vue'),
      },
      {
        path: 'categories',
        name: 'categories',
        component: () =>
          import('@/views/goods/goods-category/GoodsCategory.vue'),
      },
      {
        path: 'orders',
        name: 'orders',
        component: () => import('@/views/order/OrderList.vue'),
      },
      {
        path: 'reports',
        name: 'reports',
        component: () => import('@/views/reports/ReportsEcharts.vue'),
      },
    ],
  },
  {
    path: '*',
    component: None404,
  },
]

const router = new VueRouter({
  routes,
})

// 路由守卫导航判断 token
router.beforeEach((to, from, next) => {
  // do someting
  const token = localStorage.getItem('token') || ''
  NProgress.start()

  // 如果存在 token，或者是登录请求，过
  if (token || to.path === '/login') {
    next()
  }
  // 否则，转到 login 页
  else {
    next({
      path: '/login',
    })
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
